import socket


class Server:

    def __init__(self, configDic):
        #This is the IRC server to connect to
        self.HOST = configDic['HOST']
        #Port on the server to connect to Usually 6667 or 7000 for SSL
        self.PORT = configDic['PORT']
        #Nick name for the bot
        self.NICK = configDic['NICK']
        #Idenity name
        self.IDENT = configDic['IDENT']
        #Real Name
        self.REALNAME = configDic['REALNAME']
        #Inital channels to start in
        self.CHANNELINIT = configDic['CHANNELINIT']
        #Used to store messages from the server
        self.readBuffer = ''
        #First we create the socket
        self.aSocket = socket.socket()


    def connectToServer(self):
        '''Now we need to connect to the server'''
        #Make the connection to the server on the specified port
        print("Connecting to the server " + self.HOST + ":" + self.PORT.__str__())
        self.aSocket.connect((self.HOST, self.PORT))
        #Send the Bot nick to the server
        print('Using ' + self.NICK + ' Nickname')
        self.aSocket.send(bytes('NICK ' + self.NICK + '\r\n', 'UTF-8'))
        #Identify yourself to the server
        print("Connecting with Identity: " + self.IDENT + " and RealName: " + self.REALNAME)
        self.aSocket.send(bytes('USER ' + self.IDENT + ' ' + self.HOST + ' bla :' + self.REALNAME + '\r\n', 'UTF-8'))

        self.__chanAutoJoin()

    def joinChannel(self, chan):

        print("Joining channel: " + self.CHANNELINIT)
        self.sendMessage('JOIN ' + chan)


    def sendMessage(self, someMessage):
        '''
        This method will let other methods send messages to the server
        '''
        self.aSocket.send(bytes(someMessage + '\r\n', 'UTF-8'))

    def getLine (self):
        '''
        This method is to abstract the getting of the line
        '''
        try:
            #receive some server messages

            self.readBuffer = self.readBuffer + bytes.decode(self.aSocket.recv(1024))
            tempIn = str.split(self.readBuffer, "\n")
            self.readBuffer = tempIn.pop()

        except UnicodeDecodeError:
            print("There was an error decoding some Unicode from the server...")

        if (tempIn == None):
            '''This is risky but if the getline fails to decode the input from the server, try agian
            '''
            self.getLine()

        for line in tempIn:
                line = str.rstrip(line)
                line = str.split(line)

        '''Pi(o)ng Detection'''
        if (line[0] == "PING"):
            self.__sendPong(line[1])

        '''Auto Connect to channel'''

        return line

    def __sendPong (self, reply):
        '''This method sends a PONG reply to the server with the supplied reply'''

        '''Might be able to make the reply as part of the server config since 
        the pong reply is just the FQDN of the IRC serer'''

        print("Sending PONG to server")
        self.sendMessage("PONG " + reply)

    def __chanAutoJoin (self):
        '''This method is launchd after connection to the server and
            waits for your server to confirm the bot is identified on
            the server then calls join
            '''
        line = self.getLine()
        while line != [":" + self.NICK, 'MODE', self.NICK, ':+i']:
            print(line)
            line = self.getLine()

        print(line)
        self.joinChannel(self.CHANNELINIT)


